

const path = require('path');
const fs = require('fs');

function getDayStamp() {
    let now = new Date();
    let y = now.getFullYear();
    let m = now.getMonth() + 1;
    let d = now.getDate();
    return `${y}-${m}-${d}`;
}

function getCurFormatTime(){
    let now = new Date();
    let y = now.getFullYear();

    let m = now.getMonth() + 1;
    if(m < 10){
        m = '0' + m;
    }

    let d = now.getDate();
    if(d < 10){
        d = '0' + d;
    }

    let h = now.getHours();
    if(h < 10){
        h = '0' + h
    }

    let min = now.getMinutes();
    if(min < 10){
        min = '0' + min;
    }

    let sec = now.getSeconds();
    if(sec < 10){
        sec = '0' + sec;
    }
    return `${y}-${m}-${d} ${h}:${min}:${sec}`;
}

//
let logUtils = {
    dayTime:null,
    infoFile:null,
    errFile:null,

    _writeTo(file,msg){
        fs.appendFile(file,`${getCurFormatTime()}   ${msg}\n`,err=>{
            if(err){
                throw err;
            }
        });
    },

    info(){
        this.checkNewDay();
        let msg = Array.prototype.join.call(arguments,' ');
        this._writeTo(this.infoFile,msg);
    },
    err(){
        this.checkNewDay();
        let msg = Array.prototype.join.call(arguments,' ');
        this._writeTo(this.errFile,msg);
    },
    checkNewDay(){
        let curStamp = getDayStamp();
        let bNewDay = this.dayTime !== curStamp;
        if(bNewDay){
            this.dayTime = curStamp;
            this.infoFile = path.join(__dirname,"../logs/info_" + curStamp +".log");
            this.errFile = path.join(__dirname,"../logs/err_"+curStamp+".log");
        }
    },
};

module.exports = logUtils;
